﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Shop.Infrastructure.Paged
{
    /// <summary>
    /// 如果不希望PagedList自动分页，请使用PagedList(IEnumerable<T> source, ……)
    /// </summary>
    /// <typeparam name="T"></typeparam>
    [Serializable]
    public class PagedList<T> : List<T>, IPagedList<T>
    {
        #region constructot
        /// <summary>
        /// Ctor
        /// </summary>
        /// <param name="source">source</param>
        /// <param name="pageIndex">Page index</param>
        /// <param name="pageSize">Page size</param>
        public PagedList(IQueryable<T> source, int pageIndex, int pageSize)
            : this(pageIndex, pageSize, source.Count())
        {
            this.AddRange(source.Skip(this.PageIndex * this.PageSize).Take(this.PageSize).ToList());
        }

        /// <summary>
        /// Ctor
        /// </summary>
        /// <param name="source">source</param>
        /// <param name="pageIndex">Page index</param>
        /// <param name="pageSize">Page size</param>
        public PagedList(IList<T> source, int pageIndex, int pageSize)
            : this(pageIndex, pageSize, source.Count())
        {
            this.AddRange(source.Skip(this.PageIndex * this.PageSize).Take(this.PageSize).ToList());
        }

        /// <summary>
        /// Ctor
        /// </summary>
        /// <param name="source">source</param>
        /// <param name="pageIndex">Page index</param>
        /// <param name="pageSize">Page size</param>
        /// <param name="totalCount">Total count</param>
        public PagedList(IEnumerable<T> source, int pageIndex, int pageSize, int totalCount)
            : this(pageIndex, pageSize, totalCount)
        {
            this.AddRange(source);
        }

        public PagedList(int pageIndex, int pageSize, int totalCount)
        {
            this.PageSize = pageSize;
            this.PageIndex = pageIndex;
            this.TotalCount = totalCount;
            this.TotalPages = this.TotalCount / this.PageSize;

            if (this.TotalCount % this.PageSize > 0)
                this.TotalPages++;
        }
        #endregion

        public int PageIndex
        {
            get;
            private set;
        }
        public int PageSize
        {
            get;
            private set;
        }
        public int TotalCount
        {
            get;
            private set;
        }
        public int TotalPages
        {
            get;
            private set;
        }

        public bool HasPreviousPage
        {
            get
            {
                return (PageIndex > 0);
            }
        }
        public bool HasNextPage
        {
            get
            {
                return (PageIndex + 1 < TotalPages);
            }
        }
    }
}
